import 'dart:async';
import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/components/button_components/base_bottom_sheet_button_bar.dart';
import 'package:x3_component_core/components/layout_components/base_scaffold_component.dart';
import 'package:x3_component_core/components/selector_components/sub_level_multi/base_sub_level_multi_item.dart';
import 'package:x3_component_core/models/base_custom_checkbox_tile_model.dart';
import 'package:x3_component_core/models/base_sub_level_multi_selector_model.dart';

class BaseSubLevelMultiSelector extends StatefulWidget {
  static String sName = 'BaseSubLevelMultiSelector';

  /// 标题
  final String title;

  /// 数据行
  final List<BaseSubLevelMultiSelectorModel> dataSource;

  /// 子数据装饰器
  final BaseCustomCheckboxListTileModel Function(dynamic) decorator;

  /// 子 Widget装饰器
  final Widget Function(BaseCustomCheckboxListTileModel) itemWidgetDecorator;

  /// 是否采用静态数据
  final bool isStaticData;

  /// 是否搜索
  final bool isSearch;

  /// 最多限制选择
  final int limit;

  BaseSubLevelMultiSelector({
    Key key,
    @required this.title,
    @required this.dataSource,
    this.decorator,
    this.itemWidgetDecorator,
    this.isStaticData = false,
    this.isSearch = false,
    this.limit,
  })  : assert(title != null),
        assert(dataSource != null),
        super(key: key);
  @override
  _BaseSubLevelMultiSelectorState createState() => _BaseSubLevelMultiSelectorState();
}

class _BaseSubLevelMultiSelectorState extends State<BaseSubLevelMultiSelector> {
  /// 共享数据
  BaseSubLevelMultiDataStore _dataStore;

  /// 是否构建过子级内容 -- 填入父级id
  List<String> _isLoadedChildren = [];

  /// 控制流
  final StreamController<List<BaseSubLevelMultiSelectorModel>> _resetStreamController = StreamController<List<BaseSubLevelMultiSelectorModel>>.broadcast();
  @override
  void initState() {
    _dataStore = BaseSubLevelMultiDataStore(dataSource: widget.dataSource);
    super.initState();
  }

  /// 创建页面
  @override
  Widget build(BuildContext context) {
    return BaseScaffoldComponent(
      title: widget.title,
      footerWidget: _buildFooterWidget(),
      child: Column(
        children: [
          Expanded(
            child: Provider(
              create: (_) => _dataStore,
              child: ListView.builder(shrinkWrap: true, itemBuilder: _buildContent, itemCount: _dataStore.dataSource.length),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建父级card list
  Widget _buildContent(BuildContext context, int index) {
    BaseSubLevelMultiSelectorModel item = _dataStore.dataSource[index];
    if (widget.isStaticData == true) {
      if (!_isLoadedChildren.contains(item.id)) _isLoadedChildren.add(item.id);
    }
    return Consumer<BaseSubLevelMultiDataStore>(
      builder: (BuildContext context, BaseSubLevelMultiDataStore store, Widget child) {
        return BaseSubLevelMultiItem(
          key: Key(index.toString()),
          index: index,
          resetStreamController: _resetStreamController,
          isSearch: widget.isSearch,
          store: store,
          decorator: widget.decorator,
          itemWidgetDecorator: widget.itemWidgetDecorator,
          isStaticData: widget.isStaticData,
          loadedCallBack: (BaseSubLevelMultiSelectorModel v) {
            if (!_isLoadedChildren.contains(v.id)) _isLoadedChildren.add(v.id);
          },
        );
      },
    );
  }

  /// 构建行为按钮
  Widget _buildFooterWidget() {
    return BaseBottomSheetButtonBar(
      completeText: '完成',
      onComplete: _onSave,
      cancelText: '重置',
      onCancel: _onReset,
    );
  }

  /// 重置
  void _onReset() {
    _isLoadedChildren = _dataStore.dataSource.map((e) => e.id).toList();
    _resetStreamController.add(_dataStore.dataSource);
    setState(() {});
  }

  /// 保存
  void _onSave() {
    List<BaseCustomCheckboxListTileModel> datas = [];
    for (int i = 0; i < _dataStore.dataSource.length; i++) {
      List<BaseCustomCheckboxListTileModel> data = _dataStore.dataSource[i].selectedChildrenKey.map((e) => _dataStore.dataSource[i].children[e]).toList();
      datas.addAll(data);
    }
    if (widget.limit != null) {
      if (datas.length > widget.limit) {
        BaseUtils.showToast('最多选择${widget.limit}个');
        return;
      }
    }
    BaseRouterUtil().pop<BaseSubLevelMultiSelectorCallBack>(BaseSubLevelMultiSelectorCallBack(dataSource: datas, loadedChildren: _isLoadedChildren));
  }

  @override
  void dispose() {
    _resetStreamController.close();
    super.dispose();
  }
}

/// 多选器与父级数据共享
class BaseSubLevelMultiDataStore {
  final List<BaseSubLevelMultiSelectorModel> dataSource;
  final Map<int, Set<int>> dataSourceSelectedKey = {};

  BaseSubLevelMultiDataStore({@required this.dataSource}) : assert(dataSource != null);

  void reSet() {
    for (int i = 0; i < dataSource.length; i++) {
      dataSource[i].selectedChildrenKey?.clear();
      dataSource[i].children?.forEach((element) {
        element.isChecked = false;
      });
    }
  }
}

/// 返回类
class BaseSubLevelMultiSelectorCallBack {
  final List<BaseCustomCheckboxListTileModel> dataSource;
  final List<String> loadedChildren;

  BaseSubLevelMultiSelectorCallBack({@required this.dataSource, this.loadedChildren = const []});
}
